//
//  KLMSmartNode.swift
//  KLM
//
//  Created by 朱雨 on 2021/7/19.
//

import UIKit
import nRFMeshProvision

protocol KLMSmartNodeDelegate: AnyObject {
    
    func smartNode(_ manager: KLMSmartNode, didReceiveVendorMessage message: responsParame?)
    
    func smartNodeDidResetNode(_ manager: KLMSmartNode)
    
    func smartNode(_ manager: KLMSmartNode, didfailure error: MessageError?)
}

extension KLMSmartNodeDelegate {
    
    func smartNode(_ manager: KLMSmartNode, didReceiveVendorMessage message: responsParame?){
        
    }
    
    func smartNodeDidResetNode(_ manager: KLMSmartNode){
        
    }
    
    func smartNode(_ manager: KLMSmartNode, didfailure error: MessageError?){
        
    }
}

class KLMSmartNode: NSObject {
    
    var currentNode: Node?
    var command: KLMSigMeshCommand?
    
    static let sharedInstacnce = KLMSmartNode()
    private override init(){
        super.init()
        
    }
    
    weak var delegate: KLMSmartNodeDelegate?
    
    /// isCanInternet 是否能网络
    func sendMessage(_ parame: parameModel, toNode node: Node, isCanInternet: Bool? = true) {

        if let model = KLMHomeManager.getModelFromNode(node: node) {
            
            currentNode = node
            KLMMeshNetworkManager.shared.delegate = self
            
            let parameString = parame.value!
            let dpString = parame.dp!.rawValue.decimalTo2Hexadecimal()
            
            /// 满足能网络控制，同时有网关在线
//            if isCanInternet == true && KLMRemoteManager.shared.isRemote {
//                let opCode = "DAFF00"
//                KLMService.remoteControlDevice(groupControl: 0, unicastAddress: node.unicastAddress, opCode: opCode, dpCode: dpString, cfgInfo: parameString) { response in
//                    guard let data: RemoteData = response as? RemoteData, let command = data.cfgInfo else {
//                        let err = MessageError()
//                        err.dp = parame.dp
//                        err.message = KLMLocalizable.LANGLOC("Device Offline")
//                        self.delegate?.smartNode(self, didfailure: err)
//                        return
//                    }
//                    let dd = Data(hex: command)
//                    if dd.count >= 2 {
//                        ///状态 0为成功  其他为失败
//                        let status = dd[0]
//                        /// dp点
//                        let dpData = dd[1]
//                        /// 数据
//                        let value: Data = dd.suffix(from: 2)
//                        
//                        self.handleMessage(opcode: .send, status: status, dpData: dpData, value: value)
//                    }
//                    
//                } failure: { error in
//                    let err = MessageError()
//                    err.dp = parame.dp
//                    err.message = error.localizedDescription
//                    self.delegate?.smartNode(self, didfailure: err)
//                }
//                return
//            }
            
            ///开始定时
            let command = KLMSigMeshCommand()
            command.timeout = 6
            self.command = command
            
            if let opCode = UInt8("1A", radix: 16) {
                let parameters = Data(hex: dpString + parameString)
                KLMLog("parameter = \(parameters.hex)")
                let message = RuntimeVendorMessage(opCode: opCode, for: model, parameters: parameters)
                do {
                    
                    command.messageHandle = try MeshNetworkManager.instance.send(message, to: model)
                    startTimer(dp: parame.dp)
                } catch {
                    let err = MessageError()
                    err.dp = parame.dp
                    err.message = error.localizedDescription
                    self.delegate?.smartNode(self, didfailure: err)
                    
                }
            }
        } else {
            let err = MessageError()
            err.dp = parame.dp
            err.message = KLMLocalizable.LANGLOC("model not found")
            self.delegate?.smartNode(self, didfailure: err)
        }
    }
    
    func readMessage(_ parame: parameModel, toNode node: Node, isCanInternet: Bool? = true) {
            
        if let model = KLMHomeManager.getModelFromNode(node: node) {
            
            currentNode = node
            KLMMeshNetworkManager.shared.delegate = self
            
            var dpString = parame.dp!.rawValue.decimalTo2Hexadecimal()
            if let value = parame.value {
                dpString = dpString + value
            }
//            if isCanInternet == true && KLMRemoteManager.shared.isRemote {
//                let opCode = "DCFF00"
//                KLMService.remoteSelectDevice(unicastAddress: node.unicastAddress, opCode: opCode, dpCode: dpString) { response in
//                    guard let data: RemoteData = response as? RemoteData, let command = data.cfgInfo else {
//                        let err = MessageError()
//                        err.dp = parame.dp
//                        err.message = KLMLocalizable.LANGLOC("Device Offline")
//                        self.delegate?.smartNode(self, didfailure: err)
//                        return
//                    }
//                    let dd = Data(hex: command)
//                    if dd.count >= 2 {
//                        ///状态 0为成功  其他为失败
//                        let status = dd[0]
//                        /// dp点
//                        let dpData = dd[1]
//                        /// 数据
//                        let value: Data = dd.suffix(from: 2)
//                        
//                        self.handleMessage(opcode: .read, status: status, dpData: dpData, value: value)
//                    }
//                    
//                } failure: { error in
//                    let err = MessageError()
//                    err.dp = parame.dp
//                    err.message = error.localizedDescription
//                    self.delegate?.smartNode(self, didfailure: err)
//                }
//                return
//            }
            
            let command = KLMSigMeshCommand()
            command.timeout = 6
            self.command = command
            
            if let opCode = UInt8("1C", radix: 16) {
                let parameters = Data(hex: dpString)
                KLMLog("readParameter = \(parameters.hex)")
                let message = RuntimeVendorMessage(opCode: opCode, for: model, parameters: parameters)
                do {
                
                    command.messageHandle = try MeshNetworkManager.instance.send(message, to: model)
                    startTimer(dp: parame.dp)
                } catch  {
                    
                    let err = MessageError()
                    err.dp = parame.dp
                    err.message = error.localizedDescription
                    self.delegate?.smartNode(self, didfailure: err)
                }
            }
        } else {
            let err = MessageError()
            err.dp = parame.dp
            err.message = KLMLocalizable.LANGLOC("model not found")
            self.delegate?.smartNode(self, didfailure: err)
        }
    }
    
    /// 删除节点
    func resetNode(node: Node) {
        
        currentNode = node
        KLMMeshNetworkManager.shared.delegate = self
        
        let command = KLMSigMeshCommand()
        command.timeout = 6
        self.command = command
        
        let message = ConfigNodeReset()
        do {
            command.messageHandle = try MeshNetworkManager.instance.send(message, to: node)
            startTimer(dp: nil)
        } catch  {
            
            let err = MessageError()
            err.message = error.localizedDescription
            self.delegate?.smartNode(self, didfailure: err)
        }
    }
    
    private func handleMessage(opcode: opCodeType, status: UInt8, dpData: UInt8, value: Data) {
        
        var response = responsParame()
        response.opCode = opcode
        
        let dp = DPType(rawValue: Int(dpData))
        response.dp = dp
                            
        if status != 0 { ///返回错误

            let err = MessageError()
            err.code = Int(status)
            err.dp = dp
            switch status {
            case 1:
                if dp == .cameraPic {
                    err.message = KLMLocalizable.LANGLOC("The light failed to connect to Wi-Fi. Maybe the Wi-Fi password is incorrect")
                }
                if dp == .category {
                    err.message = KLMLocalizable.LANGLOC("The device does not support")
                }
                if dp == .newBiaoding {
                    err.message = "标定数据传输失败，请检查网络。"
                }
                if dp == .dataRelayOTA {
                    err.message = KLMLocalizable.LANGLOC("Failed to connect to Network")
                }
                if dp == .customerColor {
                    err.message = KLMLocalizable.LANGLOC("Data exception")
                }
            case 2:
                err.message = KLMLocalizable.LANGLOC("Please turn the light on")
            case 3:
                err.message = KLMLocalizable.LANGLOC("Light locked, please contact seller")
            case 4: ///设备WiFi爆出的错误。
                KLMLog("可能是5GHz Wi-Fi或找不到此Wi-Fi")
                err.message = KLMLocalizable.LANGLOC("This may be a 5 GHz Wi-Fi, or Wi-Fi could not be found")
            case 5:
                KLMLog("设备与此Wi-Fi较远,无法建立连接")
                err.message = KLMLocalizable.LANGLOC("The device is too far away from Wi-Fi Router,so it can not connect to Wi-Fi")
            case 0xFF:
                err.message = KLMLocalizable.LANGLOC("The device does not support")
            case 0xFE:
                err.message = KLMLocalizable.LANGLOC("Sensor failure")
            case 0xFB:
                err.message = KLMLocalizable.LANGLOC("The temperature of sensor is too high")
            case 0xFA:
                err.message = KLMLocalizable.LANGLOC("Spotlight is in demo mode.The time interval in 'Auto Mode' should be more than 10 minutes.")
            case 0xFC:
                err.message = KLMLocalizable.LANGLOC("Product popularity sensor failured")
            case 0xFD:
                err.message = KLMLocalizable.LANGLOC("Auto Mode sensor failure")
            default:
                err.message = KLMLocalizable.LANGLOC("Data exception")
            }
            self.delegate?.smartNode(self, didfailure: err)
            return
        }
        
        if value.count == 0 { ///没有字节
            let err = MessageError()
            err.code = Int(status)
            err.dp = dp
            err.message = KLMLocalizable.LANGLOC("Data exception")
            self.delegate?.smartNode(self, didfailure: err)
            return
        }
        
        //返回成功也要卡住一些错误数据
        switch dp {
        case .cameraPic: ///为了兼容旧版灯具，旧款灯具会大于7个字节
            if value.count > 7 { ///数据有误
                let err = MessageError()
                err.code = 1
                err.dp = dp
                err.message = KLMLocalizable.LANGLOC("The device does not support")
                self.delegate?.smartNode(self, didfailure: err)
                return
            }
        default:
            break
        }
        
        switch response.dp {
        case .power,
             .colorTemp,
             .light,
             .cameraPower,
             .flash,
             .category,
             .encryption,
             .master,
             .oreMotorAction,
             .sceneHuyan,
             .manualTrigger,
             .duandian,
             .customerCounting:
            
            response.value = Int(value.bytes[0])
        case .color,
             .cameraPic,
             .dataRelayOTA,
             .hardwareInfo,
             .audio,
             .biaoding,
             .controllerRGB,
             .controllerShuangse,
             .customerColor,
             .powerSetting,
             .customerCountingPower,
             .dianliu,
             .Dali,
             .danse,
             .colorTempLimit,
             .newBiaoding,
             .allTest,
             .lightLimit,
             .motion,
             .panelScene1,
             .panelScene2,
             .panelScene3,
             .panelSingleFire,
             .oreMotorTime,
             .defaultCMOS,
             .kandian,
             .DataRelay,
             .autoDetectFine,
             .brightness,
             .productionMark,
             .deviceSetting:
            
            response.value = [UInt8](value)
        case .recipe, //不处理结果
             .colorTest,
             .RKWifiMessage,
             .PWM:
            response.value = value
        case .factoryTest,
             .factoryTestResule:
            response.value = value.hex

        default:
            break
        }
        
        self.delegate?.smartNode(self, didReceiveVendorMessage: response)
    }
    
    ///开启定时
    private func startTimer(dp: DPType?) {

        if dp == .cameraPic {
            command?.timeout = 20
        } else if dp == .power {
            command?.timeout = 4
        } else if dp == .customerCounting {
            command?.timeout = 25
        } else if dp == .RKWifiMessage {
            command?.timeout = 60
        }
        
        //开始计时
        command?.startTimer { [weak self] error in
            guard let self = self else { return }
            ///超时取消消息发送
            self.command?.messageHandle?.cancel()
            let err = MessageError()
            err.dp = dp
            err.code = timeOutCode
            err.message = KLMLocalizable.LANGLOC("Connection timed out.") + KLMLocalizable.LANGLOC("Make sure the device is powered on and near your device.")
            self.delegate?.smartNode(self, didfailure: err)
        }
    }
}

extension KLMSmartNode: MeshNetworkDelegate {
    
    func meshNetworkManager(_ manager: MeshNetworkManager, didReceiveMessage message: MeshMessage, sentFrom source: Address, to destination: Address) {
        
        ///收到回复，停止计时
        command?.commandResponseFinishWithCommand()
        switch message {
        case let message as UnknownMessage://收发消息
            if let parameters = message.parameters {
                //如果是开关 "0101"
                KLMLog("messageResponse = \(parameters.hex)")
                
                if parameters.count >= 2 {
                    
                    ///不是当前节点的消息不处理
                    if source != currentNode?.unicastAddress {
                        KLMLog("别的节点回的消息")
                        return
                    }
                    
                    var opCode: opCodeType = .send
                    if message.opCode.hex() == "00DD00FF" {
                        KLMLog("读到的消息是 = \(parameters.hex)")
                        opCode = .read
                    } else if message.opCode.hex() == "00DB00FF" {
                        KLMLog("发送消息回复 = \(parameters.hex)")
                        opCode = .send
                    } else {
                        KLMLog("是其他消息，比如升级消息")
                        return
                    }
                    ///状态 0为成功  其他为失败
                    let status = parameters[0]
                    /// dp点
                    let dpData = parameters[1]
                    /// 数据
                    let value: Data = parameters.suffix(from: 2)
                    
                    handleMessage(opcode: opCode, status: status, dpData: dpData, value: value)
                
                }
            }
        case is ConfigNodeResetStatus:
            self.delegate?.smartNodeDidResetNode(self)
        default:
            break
        }
    }
    
    func meshNetworkManager(_ manager: MeshNetworkManager, didSendMessage message: MeshMessage, from localElement: Element, to destination: Address) {
        
        
    }
    
    func meshNetworkManager(_ manager: MeshNetworkManager, failedToSendMessage message: MeshMessage, from localElement: Element, to destination: Address, error: Error) {
        ///失败停止计时
        command?.commandResponseFinishWithCommand()
        SVProgressHUD.dismiss()
        
        var dp1: DPType?
        if let parameters = message.parameters {
                        
            if parameters.count >= 1 {
                
                let dpData = parameters[0]
                let dp = DPType(rawValue: Int(dpData))
                dp1 = dp
            }
        }
        
        let err = MessageError()
        err.dp = dp1
        err.message = KLMLocalizable.LANGLOC("Make sure the device is powered on and near your device.")
        
        do {
            try KLMConnectManager.checkBluetoothState()
            
        } catch {
            
            if let errr = error as? MessageError {
                err.message = errr.message
            }
        }
         
        self.delegate?.smartNode(self, didfailure: err)
    }
}

enum nodeDeviceType: String {
    ///================轨道灯
    ///meta1
    case meta1OneCamera = "DD"
    case meta1NoCamera = "00"
    ///meta2
    case meta2OneCamera = "D0"
    case meta2TwoCamera = "D1" ///双摄像头
    case meta2NoCamera = "04"
    case meta2NoCameraC10 = "05"
    ///手持设备
    case metaG2OneCamera = "D3"
    case metaG2TwoCamera = "D2"
    case metaG2NoCamera = "D4"
    
    ///生鲜灯
    case meta2FreshOne = "D5"
    case meta2FreshTwo = "D6"
    case meta2FreshNo = "08"
    case meta2FreshC10 = "09"
    
    ///双色温调光
    case metaUniOne = "D7"
    case metaUniTwo = "D8"
    case metaUniNo = "0A"
    
    ///贝多芬 - 都是无摄像头
    case lunaWRGB = "0B" ///telink 和 meta2NoCamera 差不多
    case lunaWWCW = "0C" ///telink 和 metaUniNo 差不多
    case lunaWW = "0F" /// telink 单色温 跟 灯带控制器的单色温 只有个亮度滑条
    
    ///缪斯
    case MusesOneCamera = "A0" /// meta2OneCamera
    case MusesTwoCamera = "A1" /// meta2TwoCamera
    
    ///斗胆
    case lukaNoCamera = "0E" ///meta2NoCamera telink
    case lukaOneCamera = "DE" ///meta2OneCamera
    case lukaUniOneCamera = "DF" ///metaUniOne
    
    ///贝多芬
    case auraUniNoCamera = "0D" ///metaUniNo telink
    case auraUniOneCamera = "DA" ///metaUniOne
    
    ///宙斯
    case kanoOneCamera = "A2"
    case kanoTwoCamera = "A3"
    
    ///洗墙灯
    case wallLamp = "A4"
    case kanoUniOneCamera = "A5"
    case kanoUniTwoCamera = "A6"
    
    ///================控制器
    ///控制器
    case qieXiang = "01"
    case RGBControl = "02"
    case Dali = "03"
    case danse = "06" //单色
    case shuangse = "07" //双色
    case WWCW = "10" //步路思双路灯带 类似灯带控制器双色温负载
    
    ///================中继器
    ///中继
    case gateway = "F0" //中继器
    case gatewayNew = "F1" //网关
    
    ///================面板
    case scene1 = "31"
    case scene2 = "32"
    case scene3 = "33"
    case singleFire1 = "34"
    case singleFire2 = "35"
    case singleFire3 = "36"
    
    ///================其他
    case oreMotor = "30" ///矿石升降机
    case Accelerometer = "37" ///加速计
    case Illuminometer = "FF" ///照度计
    
    ///================RK设备
    case RKAllInOne = "59" ///空间智能传感器
    //////嵌入式场景识别控制器
    case embeddedSceneController = "60"
    ///台灯
    case tableLamp = "B0"
    ///线条灯
    case lineLamp = "B1"
}

enum RGBLoadType: Int {
    case White = 1
    case TunableWhite = 2
    case RGB = 3
    case RGBW = 4
    case RGBCW = 5
}

enum RKAllInOneType: Int {
    case sceneRecognition = 1
    case CustomerCounting = 2
    case furnitureStore = 3 ///家具
    case Heatmap = 4
}

///控制类型
enum ControlType: Int {
    case none = 0
    case RGBlight = 1
    
    ///控制器
    case RGBWhite = 2 ///单色温
    case RGBTunableWhite = 3 ///双色温
    case RGB = 4
    case RGBW = 5
    case RGBCW = 6
    case Dali = 7
    case qieXiang = 8
    case danse = 9 /// 0-10V
    case shuangse = 10 /// 0-10V
    case singleFirePanel = 11/// 单火面板
    case colorTempLight = 15 ///双色温调光
    case lunaWWType = 16 ///luna单色温
}

extension Node {
    
    var icon: String {
        return KLMSmartNode.getIcon(deviceType: deviceType)
    }
    
    /// 节点的名称
    var nodeName: String {
        
        return self.name ?? KLMLocalizable.LANGLOC("Unknown device")
    }
    ///节点uuid字符串-与服务器交互使用
    var nodeuuidString: String {
        
        let string = self.uuid.uuidString.replacingOccurrences(of: "-", with: "")
        let substring = string[4,12]
        return substring
    }
    
    ///设备类型
    var deviceType: nodeDeviceType {
        let index = uuid.uuidString[2,2]
        let type = nodeDeviceType.init(rawValue: index) ?? .meta1OneCamera
        return type
    }
    ///灯带负载
    var rgbLoadType: RGBLoadType? {
        guard let loadType = loadType else { return nil }
        let type = RGBLoadType.init(rawValue: loadType)
        return type
    }
    
    ///多合一类型
    var rkAllInOneType: RKAllInOneType? {
        guard let allInOneType = allInOneType else { return nil }
        let type = RKAllInOneType.init(rawValue: allInOneType)
        return type
    }
    
    ///控制类型
    var controlType: ControlType {
        return KLMSmartNode.getControlType(deviceType: deviceType, rgbLoadType: rgbLoadType)
    }
    
    ///是控制器
    var isController: Bool {
        return KLMSmartNode.isController(deviceType: deviceType)
    }
    
    ///是轨道灯
    var isTracklight: Bool {
        
        return KLMSmartNode.isTracklight(deviceType: deviceType)
    }
        
    ///meta1产品
    var isMeta1: Bool {
        return KLMSmartNode.isMeta1(deviceType: deviceType)
    }
    ///是否是生鲜灯
    var isFresh: Bool {
        return KLMSmartNode.isFresh(deviceType: deviceType)
    }
    
    ///双色温调光
    var isMetaUni: Bool {
        return KLMSmartNode.isMetaUni(deviceType: deviceType)
    }
    
    ///是否有摄像头
    var haveCamera: Bool {
        return KLMSmartNode.haveCamera(deviceType: deviceType)
    }
    ///有两个摄像头
    var haveTwoCamera: Bool {
        return KLMSmartNode.haveTwoCamera(deviceType: deviceType)
    }
    
    ///没有摄像头的轨道灯
    var trackLightNoCamera: Bool {
        return KLMSmartNode.trackLightNoCamera(deviceType: deviceType)
    }
    
    ///是Telink的设备
    var isTelinkDevice: Bool {
        return KLMSmartNode.isTelinkDevice(deviceType: deviceType)
    }
    
    ///是场景面板
    var isScenePanel: Bool {
        return KLMSmartNode.isScenePanel(deviceType: deviceType)
    }
    
    ///是单火面板
    var isSingleFirePanel: Bool {
        return KLMSmartNode.isSingleFirePanel(deviceType: deviceType)
    }
    
    ///是面板
    var isPanel: Bool {
        return KLMSmartNode.isPanel(deviceType: deviceType)
    }
    
    ///是RK平台
    var isRK: Bool {
        return KLMSmartNode.isRK(deviceType: deviceType)
    }
    
    ///是否能添加到分组
    var isCanAddToGroup: Bool {
        if isTracklight || isController {
            return true
        }
        return false
    }

    ///面板按键
    var panelButtonLists: [KLMPanelButtonsModel] {
        var list = [KLMPanelButtonsModel]()
        if deviceType == .scene1 || deviceType == .singleFire1 { ///一个按键
            var model = KLMPanelButtonsModel.init()
            if deviceType == .singleFire1 {
                model.dp = .panelSingleFire
            }
            list.append(model)
        } else if deviceType == .scene2 || deviceType == .singleFire2 { ///两个按键
            var left = KLMPanelButtonsModel.init(buttonName: KLMLocalizable.LANGLOC("Left key"))
            if deviceType == .singleFire2 {
                left.dp = .panelSingleFire
            }
            list.append(left)
            
            var right = KLMPanelButtonsModel.init(buttonName: KLMLocalizable.LANGLOC("Right key"), dp: .panelScene2, buttonIndex: 1)
            if deviceType == .singleFire2 {
                right.dp = .panelSingleFire
            }
            list.append(right)
        } else { /// 三个按键
            var left = KLMPanelButtonsModel.init(buttonName: KLMLocalizable.LANGLOC("Left key"))
            if deviceType == .singleFire3 {
                left.dp = .panelSingleFire
            }
            list.append(left)
            
            var middle = KLMPanelButtonsModel.init(buttonName: KLMLocalizable.LANGLOC("Middle key"), dp: .panelScene2, buttonIndex: 1)
            if deviceType == .singleFire3 {
                middle.dp = .panelSingleFire
            }
            list.append(middle)
            
            var right = KLMPanelButtonsModel.init(buttonName: KLMLocalizable.LANGLOC("Right key"), dp: .panelScene3, buttonIndex: 2)
            if deviceType == .singleFire3 {
                right.dp = .panelSingleFire
            }
            list.append(right)
        }
        return list
    }
        
    private static var versionKey = true
    ///版本号
    var version: String? {
        get {
            return (objc_getAssociatedObject(self, &Self.versionKey) as? String)
        }
        set {
            objc_setAssociatedObject(self, &Self.versionKey, newValue, .OBJC_ASSOCIATION_COPY)
        }
    }
}

extension Node {
    ///mesh OTA 使用
    func getAddressesWithModelID(modelID: UInt16) -> [UInt16] {
        var array: [UInt16] = [UInt16]()
        if elements.count > 0 {
            for (i, element) in elements.enumerated() {
                for model in element.models {
                    if model.modelIdentifier == modelID {
                        array.append(unicastAddress+UInt16(i))
                        break
                    }
                }
            }
        }
        return array
    }
}

///给扩展增加存储属性
extension GattBearer {
    private static var Node_KEY = true
    var manufacturer: Data {
        get {
            return (objc_getAssociatedObject(self, &Self.Node_KEY) as? Data) ?? Data.init()
        }
        set {
            objc_setAssociatedObject(self, &Self.Node_KEY, newValue, .OBJC_ASSOCIATION_COPY)
        }
    }
    
    var manufacturerNodeUUID: String {
        var uuid = ""
        if manufacturer.count >= 8 {
            let data: Data = manufacturer[2...7] ///将默认使用场合也匹配进去
            uuid = data.hex
        }
        return uuid
    }
}

extension KLMSmartNode {
        
    ///通过服务器的uuid获取节点
    static func getNodeFromNodeuuidString(nodeuuidString: String?) -> Node? {
        guard let nodeuuidString = nodeuuidString else { return nil }
        if let network = MeshNetworkManager.instance.meshNetwork {
            let notConfiguredNodes = network.nodes.filter({ !$0.isConfigComplete && !$0.isProvisioner})
            return notConfiguredNodes.first { node in
                let string = node.uuid.uuidString.replacingOccurrences(of: "-", with: "")
                if string.contains(nodeuuidString) {
                    return true
                }
                return false
            }
        }
        return nil
    }
}

struct KLMPanelButtonsModel {
    var buttonName: String = KLMLocalizable.LANGLOC("Key")
    var dp: DPType = .panelScene1
    var buttonIndex: Int = 0
}

///根据设备类型来分类
extension KLMSmartNode {
    ///设备图标
    static func getIcon(deviceType: nodeDeviceType) -> String {
        switch deviceType {
        case .qieXiang:
            return "img_RCL"
        case .RGBControl,
                .WWCW:
            return "img_RGBW"
        case .Dali:
            return "img_DA"
        case .danse,
                .shuangse:
            return "img_0_10V"
        case .gateway,
                .gatewayNew:
            return "icon_datarelay"
        case .metaG2NoCamera,
                .metaG2OneCamera,
                .metaG2TwoCamera:
            return "icon_metaG2"
        case .singleFire1:
            return "icon_singleFire_one"
        case .singleFire2:
            return "icon_singleFire_two"
        case .singleFire3:
            return "icon_singleFire_three"
        case .scene1:
            return "icon_scenePanel_one"
        case .scene2:
            return "icon_scenePanel_two"
        case .scene3:
            return "icon_scenePanel_three"
        case .embeddedSceneController,
                .RKAllInOne,
                .Accelerometer,
                .tableLamp:
            return "icon_RK"
        case .lineLamp:
//            return "icon_lineLamp"
            return "Device_type_lamp"
        default:
            return "img_scene"
        }
    }
    ///设备控制类型
    static func getControlType(deviceType: nodeDeviceType, rgbLoadType: RGBLoadType? = nil) -> ControlType {
        var type: ControlType = .none
        if isTracklight(deviceType: deviceType) || deviceType == .oreMotor {
            type = .RGBlight
            if isMetaUni(deviceType: deviceType) {
                type = .colorTempLight
            }
            if deviceType == .lunaWW {
                type = .lunaWWType
            }
        }
        switch deviceType {
        case .Dali:
            type = .Dali
        case .qieXiang:
            type = .qieXiang
        case .danse:
            type = .danse
        case .shuangse:
            type = .shuangse
        case .singleFire1,
                .singleFire2,
                .singleFire3:
            type = .singleFirePanel
        case .WWCW:
            type = .RGBTunableWhite
        default:
            break
        }
        if deviceType == .RGBControl {
            if let rgbLoadType = rgbLoadType {
                switch rgbLoadType {
                case .White:
                    type = .RGBWhite
                case .TunableWhite:
                    type = .RGBTunableWhite
                case .RGB:
                    type = .RGB
                case .RGBW:
                    type = .RGBW
                case .RGBCW:
                    type = .RGBCW
                }
            }
        }
        return type
    }
    ///是控制器
    static func isController(deviceType: nodeDeviceType) -> Bool {
        switch deviceType {
        case .qieXiang,
                .RGBControl,
                .danse,
                .shuangse,
                .WWCW,
                .Dali:
            return true
        default:
            return false
        }
    }
    ///是轨道灯
    static func isTracklight(deviceType: nodeDeviceType) -> Bool {
        switch deviceType {
        case .meta1OneCamera,
                .meta1NoCamera,
                .meta2FreshNo,
                .meta2FreshC10,
                .meta2FreshOne,
                .meta2FreshTwo,
                .metaUniOne,
                .metaUniTwo,
                .metaUniNo,
                .meta2OneCamera,
                .meta2TwoCamera,
                .meta2NoCameraC10,
                .meta2NoCamera,
                .metaG2NoCamera,
                .metaG2OneCamera,
                .metaG2TwoCamera,
                .lunaWRGB,
                .lunaWWCW,
                .lunaWW,
                .MusesOneCamera,
                .MusesTwoCamera,
                .lukaNoCamera,
                .lukaOneCamera,
                .lukaUniOneCamera,
                .auraUniNoCamera,
                .auraUniOneCamera,
                .kanoOneCamera,
                .kanoTwoCamera,
                .kanoUniOneCamera,
                .kanoUniTwoCamera,
                .wallLamp:
            return true
        default:
            return false
        }
    }
    ///meta1产品
    static func isMeta1(deviceType: nodeDeviceType) -> Bool {
        switch deviceType {
        case .meta1OneCamera,
             .meta1NoCamera:
            return true
        default:
            return false
        }
    }
    ///是否是生鲜灯
    static func isFresh(deviceType: nodeDeviceType) -> Bool {
        switch deviceType {
        case .meta2FreshNo,
             .meta2FreshC10,
             .meta2FreshOne,
             .meta2FreshTwo:
            return true
        default:
            return false
        }
    }
    ///双色温调光
    static func isMetaUni(deviceType: nodeDeviceType) -> Bool {
        switch deviceType {
        case .metaUniOne,
             .metaUniTwo,
             .metaUniNo,
             .lunaWWCW,
             .lukaUniOneCamera,
             .kanoUniOneCamera,
             .kanoUniTwoCamera,
             .auraUniNoCamera,
             .auraUniOneCamera:
            return true
        default:
            return false
        }
    }
    ///是否有摄像头
    static func haveCamera(deviceType: nodeDeviceType) -> Bool {
        switch deviceType {
        case .meta1OneCamera,
             .meta2OneCamera,
             .meta2TwoCamera,
             .metaG2OneCamera,
             .metaG2TwoCamera,
             .meta2FreshOne,
             .meta2FreshTwo,
             .metaUniOne,
             .metaUniTwo,
             .MusesOneCamera,
             .MusesTwoCamera,
             .lukaOneCamera,
             .lukaUniOneCamera,
             .auraUniOneCamera,
             .kanoOneCamera,
             .kanoTwoCamera,
             .kanoUniOneCamera,
             .kanoUniTwoCamera,
             .wallLamp:
            return true
        default:
            return false
        }
    }
    ///有两个摄像头
    static func haveTwoCamera(deviceType: nodeDeviceType) -> Bool {
        switch deviceType {
        case .meta2TwoCamera,
             .metaG2TwoCamera,
             .meta2FreshTwo,
             .metaUniTwo,
             .MusesTwoCamera,
             .kanoUniTwoCamera,
             .kanoTwoCamera:
            return true
        default:
            return false
        }
    }
    ///没有摄像头的轨道灯
    static func trackLightNoCamera(deviceType: nodeDeviceType) -> Bool {
        switch deviceType {
        case .meta1NoCamera,
                .meta2NoCamera,
                .meta2NoCameraC10,
                .metaG2NoCamera,
                .meta2FreshNo,
                .meta2FreshC10,
                .metaUniNo,
                .lunaWWCW,
                .lunaWRGB,
                .lunaWW,
                .lukaNoCamera,
                .auraUniNoCamera:
            return true
        default:
            return false
        }
    }
    ///是场景面板
    static func isScenePanel(deviceType: nodeDeviceType) -> Bool {
        switch deviceType {
        case .scene1,
                .scene2,
                .scene3:
            return true
        default:
            return false
        }
    }
    ///是单火面板
    static func isSingleFirePanel(deviceType: nodeDeviceType) -> Bool {
        switch deviceType {
        case .singleFire1,
                .singleFire2,
                .singleFire3:
            return true
        default:
            return false
        }
    }
    ///是面板
    static func isPanel(deviceType: nodeDeviceType) -> Bool {
        if isScenePanel(deviceType: deviceType) || isSingleFirePanel(deviceType: deviceType) {
            return true
        }
        return false
    }
    ///是RK平台
    static func isRK(deviceType: nodeDeviceType) -> Bool {
        switch deviceType {
        case .embeddedSceneController,
                .RKAllInOne,
                .tableLamp,
                .lineLamp,
                .gatewayNew:
            return true
        default:
            return false
        }
    }
    ///是Telink的设备
    static func isTelinkDevice(deviceType: nodeDeviceType) -> Bool {
        if isController(deviceType: deviceType) {
            return true
        }
        if isPanel(deviceType: deviceType) {
            return true
        }
        switch deviceType {
        case .meta1NoCamera,
                .meta2NoCamera,
                .meta2NoCameraC10,
                .meta2FreshNo,
                .meta2FreshC10,
                .metaUniNo,
                .lunaWWCW,
                .lunaWRGB,
                .lunaWW,
                .lukaNoCamera,
                .Accelerometer,
                .auraUniNoCamera:
            return true
        default:
            return false
        }
    }
}

